<!--
 * @Description: 车主查询-厂端
 * @Autor: 刘诗文
 * @Date: 2020-11-10 15:59:24
 * @LastEditors: 马毅
 * @LastEditTime: 2021-04-15 10:01:34
-->
<template>
  <div>
    <TopFilter :list="topFilterList" :cols="3" :labelWidth="105" @filterChange="changeHandle" @onCollapse="collapseHandle"></TopFilter>
    <FilterTable
      ref="table"
      selectionType="single"
      :isSelectColumn="false"
      :columns="columns"
      :fetchapi="fetchapi"
      :params="fetchParams"
      :datakey="'rows'"
      columnsRef="ownerQuerylsw"
      :onColumnsChange="columns => (this.columns = columns)"
      :onRowSelectChange="onRowSelectChange"
    >
      <template slot="controls">
        <AjaxButton size="small" type="primary" icon="el-icon-download" :click="ownerExportData">导出</AjaxButton>
      </template>
    </FilterTable>
    <BaseDialog :visible.sync="actions.visible" :title="actions.title" width="300" destroyOnClose :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }">
      <searchDearlerList :resData="this.resData" @dealerData="dealerData" @close="closeSetting('dealer')" />
    </BaseDialog>
    <Drawer :visible.sync="actionsOwner.visible" :title="actionsOwner.title" width="60%" destroyOnClose :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }">
      <ownerQueryPanel :formData="this.resData" @close="closeSetting('owner')" />
    </Drawer>
  </div>
</template>
<script>
import { dictionary } from '@/utils/dictMixin';
import { isFormEmpty, notifyAction, findTableItem } from '@/utils';
import { exportExcelFile } from '@/utils/index';
import { getDearlerListByTranslate } from '@/api/customerRepair/vehicleOwnerManagement/vehicleChange';
import { getProvince, getCitys, getDistrict, getRegion } from '@/api/customerRepair/customerInfo/ownerVehicleManagement';
import { getOwnerInfo, getOwnerExcelList } from '@/api/customerRepair/customerInfo/ownerVehicleManagement';
import searchDearlerList from '@/pages/customerRepair/vehicleOwnerManagement/vehicleChangeQuery/searchDearlerList';
import ownerQueryPanel from './ownerQueryPanel';
import moment from 'moment';

export default {
  name: 'ownerQuery',
  components: {
    searchDearlerList,
    ownerQueryPanel
  },
  mixins: [dictionary],
  data() {
    this.selectedData = null;
    this.BaseTable = null;
    this.resData = null;
    return {
      topFilterList: this.createTopFilterList(),
      columns: this.createTableColumns(),
      fetchapi: getOwnerInfo,
      fetchParams: { type: 'OEM', xhrAbort: true },
      actions: { visible: false, title: '', type: '' },
      actionsOwner: { visible: false, title: '', type: '' },
      dealerList: [] // 经销商列表
    };
  },
  mounted() {
    this.BaseTable = this.$refs.table;
    // 查询经销商
    this.getDearlerListByTranslate();
    // 获取省
    this.getProvine();
    // 获取省市
    this.getRegion();
  },
  methods: {
    createTopFilterList() {
      return [
        {
          type: 'INPUT',
          label: '经销商',
          fieldName: 'ownerCode',
          hidden: true,
          initialValue: ''
        },
        {
          type: 'INPUT',
          label: '经销商',
          fieldName: 'ownerShortName',
          placeholder: '请选择...',
          initialValue: '',
          readonly: true,
          unitRender: () => {
            return <el-button icon="el-icon-search" onClick={() => this.openHandler('dealer', {})}></el-button>;
          }
        },
        // {
        //   type: 'INPUT',
        //   label: '经销商',
        //   fieldName: 'ownerCode',
        //   readOnly: true,
        //   initialValue: '',
        //   unitRender: props => {
        //     return <el-button icon="el-icon-search" onClick={() => this.openHandler('dealer', {})} />;
        //   }
        // },
        {
          type: 'INPUT',
          label: '发动机号',
          fieldName: 'engineNo',
          initialValue: ''
        },
        {
          type: 'INPUT',
          label: '车牌号',
          fieldName: 'license',
          initialValue: ''
        },
        {
          type: 'SELECT',
          label: '省',
          fieldName: 'province',
          itemList: [],
          change: val => {
            this.provinceChange(val);
            let itemList = this.topFilterList.find(item => item.fieldName === 'province').itemList;
          }
        },
        {
          type: 'SELECT',
          label: '市',
          fieldName: 'city',
          itemList: [],
          change: val => {
            this.cityChange(val);
            let itemList = this.topFilterList.find(item => item.fieldName === 'city').itemList;
          }
        },
        {
          type: 'SELECT',
          label: '区县',
          fieldName: 'distinct',
          itemList: []
        },
        {
          type: 'SELECT',
          label: '客户类型',
          fieldName: 'ownerProperty',
          initialValue: '',
          itemList: this.createDictList(8011)
        },
        {
          type: 'INPUT',
          label: '证件号码',
          fieldName: 'certificateNo'
        },
        {
          type: 'SELECT',
          label: '性别',
          fieldName: 'gender',
          itemList: this.createDictList(8012)
        },
        {
          type: 'INPUT',
          label: '客户姓名',
          fieldName: 'ownerName',
          initialValue: ''
        },
        {
          type: 'INPUT',
          label: '客户手机',
          fieldName: 'mobile'
        },
        {
          type: 'RANGE_DATE',
          label: '销售日期',
          fieldName: 'salesDateStart|salesDateEnd',
          initialValue: [
            moment(new Date())
              .subtract(6, 'month')
              .format('YYYY-MM-DD'),
            moment(new Date()).format('YYYY-MM-DD')
          ]
        },
        {
          type: 'INPUT',
          label: 'VIN',
          fieldName: 'vin'
        }
      ];
    },
    createTableColumns() {
      return [
        {
          title: '序号',
          dataIndex: 'index',
          width: 70,
          fixed: 'left',
          // sorter: true,
          render: props => {
            return <span>{props.row.index + 1}</span>;
          }
        },
        {
          title: '操作',
          dataIndex: 'column-action',
          width: 70,
          render: props => {
            return (
              <div style="text-align:center">
                <el-button size="mini" type="text" onClick={() => this.openHandler('detail', props.row)}>
                  明细
                </el-button>
              </div>
            );
          }
        },
        {
          title: '经销商代码',
          dataIndex: 'OWNER_CODE',
          showOverflowTooltip: true
        },
        {
          title: '经销商名称',
          dataIndex: 'dealerName',
          showOverflowTooltip: true,
          render: props => {
            return <span>{this.getText(props.row.OWNER_CODE)}</span>;
          }
        },
        {
          title: '客户编号',
          dataIndex: 'ownerNo',
          width: 120,
          showOverflowTooltip: true
        },
        {
          title: '客户姓名',
          dataIndex: 'ownerName',
          width: 90,
          showOverflowTooltip: true
        },
        {
          title: '性别',
          dataIndex: 'gender',
          width: 90,
          showOverflowTooltip: true,
          render: props => {
            return <span>{this.createDictText(props.row.gender, 8012)}</span>;
          }
        },
        {
          title: '客户手机号',
          dataIndex: 'mobile',
          showOverflowTooltip: true
        },
        {
          title: '客户类型',
          dataIndex: 'ownerProperty',
          width: 120,
          showOverflowTooltip: true,
          dictItems: this.createDictList(8011)
        },
        {
          title: '省份',
          dataIndex: 'province',
          width: 150,
          dictItems: [],
          showOverflowTooltip: true
        },
        {
          title: '城市',
          dataIndex: 'city',
          width: 150,
          dictItems: [],
          showOverflowTooltip: true
        },
        {
          title: '区/县',
          dataIndex: 'district',
          width: 150,
          dictItems: [],
          showOverflowTooltip: true
        },
        {
          title: '居住地址',
          dataIndex: 'address',
          width: 150,
          showOverflowTooltip: true
        }
      ];
    },
    changeHandle(val) {
      // 搜索和重置都走
      let params = { ...this.fetchParams, ...val, ...{ xhrAbort: false } };
      if (params.ownerShortName && params.ownerShortName.length) {
        params.ownerCode = this.topFilterList.find(x => x.fieldName === 'ownerCode').initialValue;
      } else {
        params.ownerCode = undefined;
      }
      if (!val.ownerName && !val.license && !val.vin && !val.salesDateStart && !val.salesDateEnd) {
        return this.$notify.warning({ title: '提示信息', message: 'vin,车牌号,客户姓名,销售日期必填其一' });
      }
      if (val.salesDateStart || val.salesDateEnd) {
        let diffMonth = moment(val.salesDateEnd).diff(moment(val.salesDateStart), 'months');
        if (diffMonth > 11) return this.$notify.warning({ title: '提示信息', message: '销售起止日期跨度不能超过一年' });
      }
      this.fetchParams = params;
    },
    collapseHandle() {
      this.$nextTick(this.BaseTable.EXECUTE_RESET_HEIGHT);
    },
    onRowSelectChange(row) {
      if (!row.length) {
        this.selectedData = null;
      } else {
        this.selectedData = row[0];
      }
    },
    // 打开窗口
    openHandler(type, val) {
      if (type === 'dealer') {
        this.actions = { visible: true, title: '经销商查询', type: 'search' };
      } else if (type === 'detail') {
        this.actionsOwner = { visible: true, title: '车主明细', type: 'show' };
        this.resData = val;
      }
      console.log('哈哈哈哈');
      console.log(this.resData);
    },
    // 获取经销商数据
    dealerData(val) {
      this.topFilterList.find(x => x.fieldName === 'ownerCode').initialValue = val.dealerCode;
      this.topFilterList.find(x => x.fieldName === 'ownerShortName').initialValue = val.dealerShortname;
      this.closeSetting('dealer');
    },
    // 关闭经销商页面
    closeSetting(type) {
      if (type === 'dealer') {
        this.actions.visible = false;
      } else if (type === 'owner') {
        this.actionsOwner.visible = false;
      }
    },
    // 查询全部经销商列表
    async getDearlerListByTranslate() {
      const res = await getDearlerListByTranslate();
      if (res.resultCode === 200) {
        if (res.errMsg) {
          notifyAction(res.errMsg, 'error');
        } else {
          this.dealerList = res.data;
        }
      }
    },
    // 翻译经销商列表
    getText(val) {
      return this.dealerList.find(x => x.dealerCode === val) ? this.dealerList.find(x => x.dealerCode === val).dealerName : '';
    },
    // 清空下拉框表当控件的值和下拉列表
    clearFormItem(item) {
      item.initialValue = undefined;
      item.itemList = [];
    },
    //获取省
    async getProvine() {
      const res = await getProvince();
      this.topFilterList.find(item => item.fieldName === 'province').itemList = res.data.map(x => ({ value: x.regionId + '', text: x.regionName }));
    },
    // 获取市下拉框
    async provinceChange(regionId) {
      this.clearFormItem(this.topFilterList.find(item => item.fieldName === 'city'));
      this.clearFormItem(this.topFilterList.find(item => item.fieldName === 'distinct'));
      if (!regionId) return;
      const res = await getCitys(regionId);
      this.topFilterList.find(item => item.fieldName === 'city').itemList = res.data.map(x => ({ value: x.regionId, text: x.regionName }));
    },
    // 获取区下拉框
    async cityChange(regionId) {
      this.clearFormItem(this.topFilterList.find(item => item.fieldName === 'distinct'));
      if (!regionId) return;
      const res = await getDistrict(regionId);
      this.topFilterList.find(item => item.fieldName === 'distinct').itemList = res.data.map(x => ({ value: x.regionId, text: x.regionName }));
    },
    // 获取省市
    async getRegion() {
      const allRegion = await getRegion();
      let regionList = allRegion.data.map(x => ({ value: x.regionId + '', text: x.regionName }));
      let targetTableItems = [findTableItem(this.columns, 'province'), findTableItem(this.columns, 'city'), findTableItem(this.columns, 'district')];
      targetTableItems.forEach(item => {
        item.dictItems = regionList;
      });
    },
    // 车主导出
    async ownerExportData() {
      await getOwnerExcelList(this.fetchParams).then(res => {
        console.log(res);
        exportExcelFile(res.data, '车主信息');
      });
    }
  }
};
</script>
<style lang="less" scoped></style>
